package cc.siyecao.fastdfs.command.storage;


import cc.siyecao.fastdfs.model.Metadata;
import cc.siyecao.fastdfs.model.RecvPackageInfo;
import cc.siyecao.fastdfs.protocol.ProtocolConstants;
import cc.siyecao.fastdfs.util.ProtocolUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Set;

/**
 * 读取文件标签
 *
 * @author lyt
 */
public class GetMetadataCommand extends FdfsStorageCommand<Set<Metadata>> {
    /**
     * 读取文件标签(元数据)
     *
     * @param groupName
     * @param remoteFileName
     */
    public GetMetadataCommand(String groupName, String remoteFileName) {
        this.groupName = groupName;
        this.fileName = remoteFileName;
    }

    @Override
    protected void send(OutputStream out, Charset charset) throws Exception {
        byte[] header;
        byte[] groupBytes;
        byte[] fileNameBytes;
        byte[] bs;
        int groupLen;

        groupBytes = new byte[ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN];
        bs = groupName.getBytes( charset );
        fileNameBytes = fileName.getBytes( charset );

        Arrays.fill( groupBytes, (byte) 0 );
        if (bs.length <= groupBytes.length) {
            groupLen = bs.length;
        } else {
            groupLen = groupBytes.length;
        }
        System.arraycopy( bs, 0, groupBytes, 0, groupLen );
        header = ProtocolUtil.packHeader( STORAGE_PROTO_CMD_GET_METADATA, groupBytes.length + fileNameBytes.length, (byte) 0 );
        byte[] wholePkg = new byte[header.length + groupBytes.length + fileNameBytes.length];
        System.arraycopy( header, 0, wholePkg, 0, header.length );
        System.arraycopy( groupBytes, 0, wholePkg, header.length, groupBytes.length );
        System.arraycopy( fileNameBytes, 0, wholePkg, header.length + groupBytes.length, fileNameBytes.length );
        out.write( wholePkg );
    }

    @Override
    protected Set<Metadata> receive(InputStream in, Charset charset) throws Exception {
        RecvPackageInfo pkgInfo = ProtocolUtil.recvPackage( in, STORAGE_PROTO_CMD_RESP, -1 );
        this.errno = pkgInfo.errno;
        if (pkgInfo.errno != 0) {
            return null;
        }
        return ProtocolUtil.splitMetadata( new String( pkgInfo.body, charset ) );
    }
}
